<template>
  <div class="search-post">
    <h2>搜索帖子</h2>
    <!-- 搜索表单 -->
    <el-form label-position="top" :model="searchForm" @submit.prevent="searchPosts" class="search-form">
      <el-form-item label="关键词">
        <el-input v-model="searchForm.q" placeholder="请输入关键词" />
      </el-form-item>

      <el-form-item label="话题分类">
        <el-select v-model="searchForm.topic" placeholder="请选择话题" clearable style="width: 100%">
          <el-option
            v-for="item in topicOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="排序方式">
        <el-radio-group v-model="searchForm.sort">
          <el-radio label="recent">按时间降序</el-radio>
          <el-radio label="relevance">按相关度</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-button type="primary" native-type="submit" class="w-100">搜索</el-button>
    </el-form>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">加载中...</div>

    <!-- 搜索结果 -->
    <div v-else class="search-results">
      <!-- 判断 posts 是否存在且有数据 -->
      <div v-if="Array.isArray(posts) && posts.length > 0">
        <p>共找到 {{ total }} 条结果（共 {{ totalPages }} 页）</p>
        <el-table :data="posts" stripe style="width: 100%">
          <!-- 标题 - 支持高亮 -->
          <el-table-column label="标题">
            <template #default="{ row }">
             <span v-html="highlightKeyword(row.title, searchForm.q)" />
            </template>
          </el-table-column>
          <!-- 其他列保持不变 -->
          <el-table-column prop="topic" label="话题" />
          <el-table-column prop="authorID" label="作者ID" />
          <el-table-column prop="likes" label="点赞数" />
          <el-table-column label="发布时间">
            <template #default="{ row }">
              {{ formatDate(row.CreatedAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <router-link :to="{ name: 'PostDetail', params: { id: row.ID } }">
                查看详情
              </router-link>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <!-- 无结果提示 -->
      <div v-else class="no-result">暂无匹配结果</div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import axios from '../axios'
// 搜索表单数据
const searchForm = ref({
  q: '',
  topic: '',
  sort: 'recent' as 'recent' | 'relevance'
})

// 搜索结果数据
const posts = ref<any[]>([]) // 初始化为空数组 ✅
const loading = ref(false)
const total = ref(0)
const totalPages = ref(0)

// 话题选项
const topicOptions = [
  { label: '全部', value: '' },
  { label: '技术分享', value: '技术分享' },
  { label: '吐槽', value: '吐槽' },
  { label: '社区运营', value: '社区运营' },
  { label: 'R18G', value: 'R18G' },
  { label: '简中互联网废物大赏', value: '简中互联网废物大赏' },
  { label: 'fghhj', value: 'fghhj' },
   { label: '杂谈', value: '杂谈' },
   { label: ' 我们郴州人是这样的', value: ' 我们郴州人是这样的' },
     { label: '成员 ', value: ' 成员' }
]

// 格式化日期
const formatDate = (dateStr: string): string => {
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}
// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 高亮关键词
const highlightKeyword = (text: string, keyword: string): string => {
  if (!keyword) return text
  const regex = new RegExp(`(${keyword})`, 'gi')
  return text.replace(regex, '<span class="highlight">$1</span>')
}
// 分页事件
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize
  searchPosts()
}

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage
  searchPosts()
}
// 发起搜索请求
const searchPosts = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/search', {
      params: {
        q: searchForm.value.q || undefined,
        topic: searchForm.value.topic === '' ? undefined : searchForm.value.topic,
        sort: searchForm.value.sort
      }
    })

    const data = response.data || {}

    // ✅ 确保 posts 总是一个数组
    posts.value = Array.isArray(data.posts) ? data.posts : []

    total.value = data.total || 0
    totalPages.value = data.totalPages || 0
  } catch (error) {
    console.error('搜索失败:', error)
    posts.value = [] // 出错时也保证是数组
  } finally {
    loading.value = false
  }
}
</script>
<style scoped>
.highlight {
  background-color: #ffeeba;
  color: #856404;
  padding: 2px 4px;
  border-radius: 3px;
}
.search-post {
  max-width: 960px;
  margin: 40px auto;
  padding: 30px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.search-form {
  max-width: 600px;
  margin: 0 auto 30px;
}

.loading {
  text-align: center;
  font-size: 16px;
  color: #7f8c8d;
}

.no-result {
  text-align: center;
  color: #999;
  font-size: 14px;
  margin-top: 20px;
}

.search-results .el-table {
  border-radius: 8px;
  overflow: hidden;
}
</style>